package ThreadTest;

/**
 * @author 刘全
 * @date 2021/8/7
 */
public class Ticket implements Runnable {
    private static int count = 100;
    private static Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            //synchronized (obj) {
            synchronized (this) {//此时this指传递进来的锁对象为TicketTest类中的t对象
                //                  而传入的t对象只有一个符合锁对象唯一的要求,故能解决线程的安全问题
                if (count == 0) {
                    break;
                } else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName() + "正在卖了一张票,还剩" + count + "张票");
                }
            }
        }
    }
}
